<?php
namespace Home\Controller;

class UserController extends \Home\Controller\BaseController
{
	/**
	 * 用户登录
	 * @author 刘新
	 */
	public function login()
	{
		$param = I('params');
		$result = D('User')->login($param);
		$this->ajaxReturn($result);
	}
	
	/**
	 * 用户退出登录
	 * @author 刘新
	 */
	public function logout()
	{
		$param = I('params');
		$result = D('User')->logout($param);
		$this->ajaxReturn($result);
	}
	
	/**
	 * 用户注册
	 * @author 刘新
	 */
	public function register()
	{
		$param = I('params');
		$result = D('User')->addUser($param);
		$this->ajaxReturn($result);
	}
	
	/**
	 * 注册发送短信
	 * @author 刘新
	 */
	public function registerSms()
	{
		$this->sms();
	}
	
	/**
	 * 发送短信
	 * @author 刘新
	 */
	public function sms()
	{
		$param = I('params');
		//获取手机号并验证
		$mobile = $param['mobile'];
		$this->ajaxReturn($this->sendSms($mobile));
	}

	/**
	 * 修改支付密码
	 */
	public function changePayPwd(){
		$param = I('params');
		$oldPass = $param['oldPwd'];
		$newPass =$param['newPwd'];
		$loginPass = $param['loginPwd'];

		if(!$oldPass || !$newPass || !$loginPass) $this->ajaxReturn(array('error' => 1, 'info' => '参数错误'));
		if($newPass == $oldPass) $this->ajaxReturn(array('error' => 1, 'info' => '新旧密码不能一样'));
		$res = $this->returnOne('User', array('id' => $this->user['userId']), '', 'trade_pwd');
		//查询成功
		if($res) {
			$oldPass =  \Common\Util\Util::encrypt($oldPass);
			if($res['trade_pwd'] === $oldPass) {
				$newPass = \Common\Util\Util::encrypt($newPass);
				$res = M('User')->where(array('id' => $this->user['userId']))->save(array('trade_pwd'=>$newPass));
				if($res) $this->ajaxReturn(array('error' => 0, 'info' => '更新成功'));
			} else {
				$this->ajaxReturn(array('error' => 1, 'info' => '原密码错误'));
			}
		}
		//更新失败
		if($res === false) $this->errorLog(__FILE__, __LINE__, M('User')->getDbError());
		$this->ajaxReturn(array('error' => 1, 'info' => '更新失败'));
	}
	/**
	 * 同意认证接口
	 */
	public function consentCertification(){
 		$res = $this->returnOne('User', array('id' => $this->user['userId']), '', 'authentication');
		//查询成功
		if($res['authentication']  == 0 ) {
			$res = M('User')->where(array('id' => $this->user['userId']))->save(array('authentication'=>'1'));
			if($res) $this->ajaxReturn(array('error' => 0, 'info' => '更新成功'));
		}
		//更新失败
		$this->ajaxReturn(array('error' => 1, 'info' => '更新失败'));
	}
	/**
	 * 同意认证接口
	 */
	public function isCertification(){
		$res = $this->returnOne('User', array('id' => $this->user['userId']), '', 'authentication');
		//查询成功
		$detail = $this->returnOne('UserDetail', array('user_id' => $this->user['userId']), '', 'realname,social_no');
		$isdetail = $detail['social_no']?1:0;
		$this->ajaxReturn(array('error' => 0, 'authentication' => $res['authentication'],'detail'=>$isdetail));
		//更新失败

	}
	/**
	 * 发送短信，内部调用
	 * @param string $mobile
	 * @author 刘新
	 */
	private function sendSms($mobile)
	{
		if(!preg_match('/^1\d{10}$/', $mobile)) return array('error' => 1, 'info' => '手机号格式错误');
		//查询
		$res = $this->returnOne('Sms', array('mobile' => $mobile), 'expire_time desc');
		
		if($res && $res['expire_time'] && $res['expire_time'] > time()) {
			$this->ajaxReturn(array('error' => 1, 'info' => '请勿重复点击'));
		}
		
		//生成随机字符串
		$rand = \Common\Util\Util::randStr();
		
		//查询短信最大保存时间
		$maxTime = global_config('sms_expire_time',true);
		$maxTime = intval($maxTime ? $maxTime : 10);
		//die(json_encode(array('error' => 1, 'info' => $maxTime)));
		//入库保存
		$data['mobile'] = $mobile;
		$data['code'] = $rand;
		$data['create_time'] = time();
		$data['expire_time'] = time() + $maxTime*60;
		$data['status'] = 1;
		$res = M('Sms')->add($data);
		if(!$res) return array('error' => 1, 'info' => '发送失败1');
		
		//调用短信平台发送
		$res = \Common\Util\Util::sms($mobile, $rand);
		if(!$res) return array('error' => 1, 'info' => '发送失败');
		return array('error' => 0, 'info' => '发送成功');
	}
	
	/**
	 * 设置密码
	 * @author 刘新
	 */
	public function setPassword()
	{
		$param = I('params');
		$oldPass = I('data.oldPwd', '', '/^\w{32,64}$/', $param);
		$newPass = I('data.newPwd', '', '/^\w{32,64}$/', $param);
		$sureNewPass = I('data.sureNewPwd', '', '/^\w{32,64}$/', $param);
		if(!$oldPass || !$newPass || !$sureNewPass) $this->ajaxReturn(array('error' => 1, 'info' => '参数错误'));
		//判断两次新密码是否一致
		if($newPass !== $sureNewPass) $this->ajaxReturn(array('error' => 1, 'info' => '两次密码不一致'));
		
		//查询旧密码
		$res = $this->returnOne('User', array('id' => $this->user['userId']), '', 'login_pwd');
		
		//查询成功
		if($res) {
			$oldPass =  \Common\Util\Util::encrypt($oldPass);
			if($res['login_pwd'] === $oldPass) {
				$newPass = \Common\Util\Util::encrypt($newPass);
				$res = M('User')->where(array('id' => $this->user['userId']))->save(array('login_pwd'=>$newPass));
				if($res) $this->ajaxReturn(array('error' => 0, 'info' => '更新成功'));
			} else {
				$this->ajaxReturn(array('error' => 1, 'info' => '原密码错误'));
			}
		}
		
		//更新失败
		if($res === false) $this->errorLog(__FILE__, __LINE__, M('User')->getDbError());
		$this->ajaxReturn(array('error' => 1, 'info' => '更新失败'));
	}
	
	/**
	 * 设置密码
	 * @author 刘新
	 */
	public function setTradePassword()
	{
		$param = I('params');
		$loginPass = I('data.loginPass', '', '/^\w{32,64}$/', $param);
		$newPass = I('data.newPwd', '', '/^\w{32,64}$/', $param);
		$sureNewPass = I('data.sureNewPwd', '', '/^\w{32,64}$/', $param);
		if(!$loginPass || !$newPass || !$sureNewPass) $this->ajaxReturn(array('error' => 1, 'info' => '参数错误'));
		//判断两次新密码是否一致
		if($newPass !== $sureNewPass) $this->ajaxReturn(array('error' => 1, 'info' => '两次密码不一致'));
	
		//查询登录密码
		$res = $this->returnOne('User', array('id' => $this->user['userId']), '', 'login_pwd');
	
		//查询成功
		if($res) {
			$loginPass =  \Common\Util\Util::encrypt($loginPass);
			if($res['login_pwd'] === $loginPass) {
				$newPass = \Common\Util\Util::encrypt($newPass);
				$res = M('User')->where(array('id' => $this->user['userId']))->save(array('trade_pwd'=>$newPass));
				if($res) $this->ajaxReturn(array('error' => 0, 'info' => '更新成功'));
			} else {
				$this->ajaxReturn(array('error' => 1, 'info' => '登录密码错误'));
			}
		}
	
		//更新失败
		if($res === false) $this->errorLog(__FILE__, __LINE__, M('User')->getDbError());
		$this->ajaxReturn(array('error' => 1, 'info' => '更新失败'));
	}
	
	/**
	 * 找回密码
	 * @author 刘新
	 */
	public function forgetPassword()
	{
		$param = I('params');
		$mobile = I('data.mobile', '', '/^1\d{10}$/', $param);
		$code = I('data.code', '', '/^\d{4,6}$/', $param);
		$newPass = I('data.newPwd', '', '/^\w{32,64}$/', $param);
		$sureNewPass = I('data.sureNewPwd', '', '/^\w{32,64}$/', $param);
	
		//检验参数及判断两次新密码是否一致
		if(!$mobile || !$newPass || !$code || !$sureNewPass) $this->ajaxReturn(array('error' => 1, 'info' => '参数错误'));
		if($newPass !== $sureNewPass) $this->ajaxReturn(array('error' => 1, 'info' => '两次密码不一致'));
		
		//查询用户信息
		$return = array('error' => 1, 'info' => '重置密码失败');
		$res = $this->returnOne('User', array('mobile' => $mobile), '', 'login_pwd,id,pwd_err_count');
		
		//查询成功
		if($res) {
			//验证账号是否被锁定
			$errorCount = global_config('pwd_err_count') ? global_config('pwd_err_count') : 3;
			if($res['pwd_err_count'] >= $errorCount) $this->ajaxReturn(array('error' => 1, 'info' => '账号已被锁定'));
			
			//验证码校验
			$res = $this->returnOne('Sms', array('mobile' => $mobile, 'code' => $code));
			if($res) {
				//判断验证码是否过期
				$expireTime = time() + (global_config('sms_expire_time') ? global_config('sms_expire_time') : 5) * 60;
				if($expireTime < time()) $this->ajaxReturn(array('error' => 1, 'info' => '验证码过期'));
				
				//更新密码
				$newPass = \Common\Util\Util::encrypt($newPass);
				$res = M('User')->where(array('mobile' => $mobile))->save(array('login_pwd'=>$newPass));
				if($res) {
					$this->ajaxReturn(array('error' => 0, 'info' => '更新成功'));
				} else {
					$error = M('User')->getDbError();
					$return['info'] = '更新失败';
				}
			} else {
				$return['info'] = '验证码错误';
				$error = M('Sms')->getDbError();
			}
		} else {
			$return['info'] = '该用户不存在';
			$error = M('User')->getDbError();
		}
	
		//更新失败
		if($res === false) $this->errorLog(__FILE__, __LINE__, $error);
		$this->ajaxReturn($return);
	}
	
	/**
	 * 更新用户信息
	 * @author 刘新
	 */
	public function updateRealname()
	{
		$param = I('params');
		$data['realname'] = $param['realname'];
		$data['social_no'] = $param['social_no'];
		$res = D('UserDetail')->updateRealname($data, $this->user['userId']);
		$this->ajaxReturn($res);
	}
	
	/**
	 * 查询实名信息
	 * @author 刘新
	 */
	public function queryRealname()
	{
		$user = $this->returnOne('User', array('id' => $this->user['userId']), '', 'bit_status');
		if($user) {
			$detail = $this->returnOne('UserDetail', array('user_id' => $this->user['userId']), '', 'realname,social_no');
			if($detail) {
				$detail['isRealnameAuth'] = $user['bit_status'] & 1 ? true : false;
				$this->ajaxReturn(array('error' => 0, 'info' => $detail));
			}
		}
		
		$this->ajaxReturn(array('error' => 1, 'info' => '查询失败'));
	}


	/**
	 * 验证支付密码是否正确
	 */
	public function verificationTrade(){
		$param = I('params');
		$tradePwd = $param['tradePwd'];
		$res = $this->returnOne('User', array('id' => $this->user['userId']), '', 'trade_pwd');
		$tradePwd = \Common\Util\Util::encrypt($tradePwd);
		if($tradePwd == $res['trade_pwd']){
			$this->ajaxReturn(array('error' => 0,'info'=>array('is_trade' => 1)));
		}else{
			$this->ajaxReturn(array('error' => 1,'info'=>array( 'is_trade' => 0)));
		}
	}



	/**
	 * 支付回调接口
	 */
	public function nineteenPay(){
		$param = I('params');
		$retCode = $param['retCode'];
		$retDesc = $param['retDesc'];
		$orderSno = $param['orderSno'];
		$amount = $param['amount'];
		$Invest = M("Invest");
		$InvestInfo = $Invest->where(array("order_no"=>$orderSno))->find();
		if($InvestInfo){
			$Invest->where(array('order_no' => $orderSno))->save(array('paysuccess'=>'3'));
		}
	}
	/**
	 * 银行卡列表
	 */
	public function userbanklist(){
		$userId =  $this->user['userId'];
		$bankVerification = M("bankVerification");
		$list = $bankVerification->where(array("user_id"=>$userId,"status"=>'1'))->select();
		include_once(dirname(__FILE__).'/bankList.php');
		if(count($list)){
			$returninfo = array();
			foreach($list as $key=>$val){
				$bankcode = $val["bank_code"];
				$info = $this->bankInfo($bankcode,$bankList);
				$infoex = explode("-",$info);
				$returninfo[$key]['banklogo'] =  '/Uploads/banklogo/'.$infoex[0].".png";
				$returninfo[$key]['bankname'] = $infoex[0];
				$returninfo[$key]['banktype'] = $infoex[2];
				$returninfo[$key]['bank_code'] = $bankcode;
				$returninfo[$key]['bank_status'] = $val['status'];
			}
			$this->ajaxReturn(array('error' => 0,'info'=>$returninfo));
		}else{
			$this->ajaxReturn(array('error' => 1,'info'=>"查无数据"));
		}
	}
	public function deleteuserbanklist(){
		$userId =  $this->user['userId'];
		$param = I('params');
		$bankcode = $param["bank_code"];
		if($bankcode == ""){
			$this->ajaxReturn(array('error' => 1,'info'=>"参数不全"));
		}
		$bankVerification = M("bankVerification");
		$list = $bankVerification->where(array("user_id"=>$userId,"bank_code"=>$bankcode))->find();
		if(count($list)){
			$bankVerification->where(array("user_id"=>$userId,"bank_code"=>$bankcode))->delete();
			$this->ajaxReturn(array('error' => 0,'info'=>"删除成功"));
		}else{
			$this->ajaxReturn(array('error' => 1,'info'=>"查无数据"));
		}
	}
	/**
	 * 银行卡验证
	 */
	public function bankVerfication(){
		$param = I('params');
		$userId =  $this->user['userId'];
		$type = $param['type'];

		include_once(dirname(__FILE__).'/bankList.php');
		$info = $this->bankInfo($param['bank_code'],$bankList);
		if($type=='1'){
			$infoex = explode("-",$info);
			$this->ajaxReturn(array('error' => 0,'info'=>array("bankname"=>$infoex[0],"banktype"=>$infoex[2],'banklogo'=>'/Uploads/banklogo/'.$infoex[0].".png")));
		}
		$code = $param['code'];
//		$codecheck = D('User')->checkCode($code);
//		if($codecheck == false || $code == ""){
//			$this->ajaxReturn(array('error' => 1,'info'=>"验证码错误"));
//		}
		$pcId = "";
		foreach($bankpcId as $key=>$val){
			if(strpos($info,$val) && strpos($info,$val)>=0){
				$pcId = $key;
			}
		}
		if($pcId == ""){
			$this->ajaxReturn(array('error' => 1,'info'=>"你的银行卡不支持"));
		}

		$data['mobile'] = $param['mobile'];
		$data['bank_code'] = $param['bank_code'];
		$data['card_holder'] = $param['card_holder'];
		$data['id_type'] = $param['id_type'];
		$data['id_no'] = $param['id_no'];
		$data['status'] = '1';
		$bankVerification = M("bankVerification");
		$list = $bankVerification->where(array("user_id"=>$userId,"bank_code"=>$param['bank_code']))->find();
		if(count($list)>0){
			$res = $bankVerification->where(array("user_id"=>$userId,"bank_code"=>$param['bank_code']))->save($data);
		}else{
			$data['user_id'] = $userId;
			$res = $bankVerification->add($data);
		}
		$this->ajaxReturn(array('error' => 0,'info'=>"提交验证成功"));
		//发送验证请求
		$url = "http://114.247.40.72:443/mservice/infoverify/realNameVerify.do";

		$list = $bankVerification->where(array("user_id"=>$userId,"bank_code"=>$param['bank_code']))->find();

		$data = array();
		$data['version'] = "1.00";
		$data['merchantId'] = "190044";
		$data['mxUserId'] = $userId;
		$data['mxReqSno'] = $list['id']+10000000;
		$data['mxReqDate'] = date("YmdHis");
		$data['cardHolder'] = $param['des_card_holder'];
		$data['idType'] = "00";
		$data['idNo'] = $param['des_id_no'];
		$data['mobile'] = $param['des_mobile'];
		$data['pcId'] = $pcId;
		$data['bankCardNo'] = $param['des_bank_code'];
		$data['cardType'] = 'DEBIT';
		$data['cardAttr'] = 'PRIVATE';
		$data['notifyUrl'] = "http://121.42.145.218/Fund/bankVerification.php";
		$text = "";
		foreach($data as $key=>$val){
			$text .= $key."=".$val."&";
		}
		$text = substr($text,0,-1);
		$data['verifystring'] = md5($text.'19pay.com.cn');
		$text = "";
		foreach($data as $key=>$val){
			$text .= $key."=".$val."&";
		}
		$text = substr($text,0,-1);
		$res = $this->curl_post($url,$text);
		$res = explode("&",$res);
		$returnInfo = array();
		foreach($res as $k=>$v){
			$l = explode("=",$v);
			$returnInfo[$l[0]] = $l[1];
		}
		print_r($returnInfo);
		die();
		if($returnInfo['reqStatus'] == 'SUCCESS'){
			$res = $bankVerification->where(array("user_id"=>$userId,"bank_code"=>$param['bank_code']))->save(array("status"=>1));
			$this->ajaxReturn(array('error' => 0,'info'=>"提交验证成功"));
		}else{
			$this->ajaxReturn(array('error' => 1,'info'=>"提交验证失败"));
		}
	}
	public function curl_post($url,$data){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		// post数据
		curl_setopt($ch, CURLOPT_POST, 1);
		// post的变量
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

		$output = curl_exec($ch);
		curl_close($ch);
		return $output;
	}
	public function bankInfo($card,$bankList)
	{
		$card_8 = substr($card, 0, 8);
		if (isset($bankList[$card_8])) {
			return $bankList[$card_8];
		}
		$card_6 = substr($card, 0, 6);
		if (isset($bankList[$card_6])) {
			return $bankList[$card_6];
		}
		$card_5 = substr($card, 0, 5);
		if (isset($bankList[$card_5])) {
			return $bankList[$card_5];
		}
		$card_4 = substr($card, 0, 4);
		if (isset($bankList[$card_4])) {
			return $bankList[$card_4];
		}
		return '该卡号信息暂未录入';
	}
	/**
	 * 重置支付密码
	 *
	 */
	public function resetPaypass(){
		$param = I('params');
		$mobile = $param['mobile'];
		$veri_code = $param['veri_code'];
		$identification = $param['identification'];
		$pass = $param['pass'];
		$userId =  $this->user['userId'];

		//判断电话、身份证是否为该用户所有
		$user = M("User")->where(array("id"=>$userId))->find();
		$user_mobile = $user['mobile'];
		if($mobile != $user_mobile){
			$this->ajaxReturn(array('error' => 1,'info'=>"此电话不是该用户所有"));
		}

		$userDetail = M("UserDetail")->where(array("user_id"=>$userId))->find();
		$user_social_no = $userDetail['social_no'];
		if($user_social_no != $identification){
			$this->ajaxReturn(array('error' => 1,'info'=>"身份证验证失败"));
		}
		//判断此验证码是否是该电话的
		$sms = M("Sms")->where(array("code"=>$veri_code,"mobile"=>$mobile))->find();
		if(empty($sms)){
			$this->ajaxReturn(array('error' => 1,'info'=>"验证码验证失败"));
		}
		//更新密码
		$newPass = \Common\Util\Util::encrypt($pass);
		$res = M('User')->where(array('id' => $this->user['userId']))->save(array('trade_pwd'=>$newPass));
		if($res){
			$this->ajaxReturn(array('error' => 0, 'info' => '更新成功'));
		}else{
			$this->ajaxReturn(array('error' => 1, 'info' => '更新失败'));
		}
	}
	/**
	 *获取用户收货地址
	 */
	public function receiptlist(){
		$param = I('params');
		$userId =  $this->user['userId'];
		$res = M("Receipt")->where(array("user_id"=>$userId))->select();
		$this->ajaxReturn(array('error' => 0, 'info' => $res));
	}

	/**
	 *设置收货地址
	 */
	public function setreceipt(){
		$param = I('params');
		$userId =  $this->user['userId'];
		$id = $param['id'];
		$data['province'] = $param['province'];
		$data['user_id'] = $userId;
		$data['isdefault'] = $param['isdefault'];
		if($param['isdefault'] == '1'){
			M("Receipt")->where(array("user_id"=>$userId))->save(array("isdefault"=>2));
		}
		$data['city'] = $param['city'];
		$data['area'] = $param['area'];
		$data['address'] = $param['address'];
		$data['phone'] = $param['phone'];
		$data['username'] = $param['username'];
		$data['create_time'] = date("Y-m-d H:i:s");
		if($id){
			$res = M("Receipt")->where(array("id"=>$id))->add($data);
		}else{
			$res = M("Receipt")->add($data);
		}
		if($res){
			$this->ajaxReturn(array('error' => 0, 'info' => '新建成功'));
		}else{
			$this->ajaxReturn(array('error' => 1, 'info' => '新建失败'));
		}
	}
	public function deletereceipt(){
		$param = I('params');
		$id = $param['id'];
		$res = M("Receipt")->where(array("id"=>$id))->delete();
		if($res){
			$this->ajaxReturn(array('error' => 0, 'info' => '删除成功'));
		}else{
			$this->ajaxReturn(array('error' => 1, 'info' => '新删除失败'));
		}
	}
	//获取默认接口
	public function defaultreceipt(){
		$param = I('params');
		$userId =  $this->user['userId'];
		$res = M("Receipt")->where(array("user_id"=>$userId,"isdefault"=>'1'))->find();
		$this->ajaxReturn(array('error' => 0, 'info' => $res));
	}
	//修改默认接口
	public function changedefaulttreceipt(){
		$param = I('params');
		$userId =  $this->user['userId'];
		$id = $param['id'];
		$res = M("Receipt")->where(array("user_id"=>$userId))->save(array("isdefault"=>2));
		$res = M("Receipt")->where(array("id"=>$id))->save(array("isdefault"=>1));
		$this->ajaxReturn(array('error' => 0, 'info' => '修改成功'));
	}
	/**
	 *修改用户信息
	 */
	public function updateuserinfo(){
		$param = I('params');
		$userId =  $this->user['userId'];
		$data = array();
		$param['sex']?$data['sex'] = $param['sex']:"";
		$param['liveAddress']?$data['liveAddress'] = $param['liveAddress']:"";
		$param['nickname']?$data['nickname'] = $param['nickname']:"";
		$res = M("User")->where(array("user_id"=>$userId))->save($data);
		$this->ajaxReturn(array('error' => 0, 'info' => '修改成功'));
	}
}